package org.example.sys.exception;

import org.example.core.enums.BizErrorEnum;
import org.example.core.exception.BusinessException;
import org.example.core.web.Result;
import org.example.sys.utils.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 * @author Calvin
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ResponseBody
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e,
                                                        HttpServletResponse response) {
        CommonUtil.addCrossHeaders(response);
        return new Result<>(BizErrorEnum.RESULT_ERROR.getCode(), "请求方式不正确");
    }

    @ResponseBody
    @ExceptionHandler(AccessDeniedException.class)
    public Result<?> accessDeniedExceptionHandler(AccessDeniedException e, HttpServletResponse response) {
        CommonUtil.addCrossHeaders(response);
        return new Result<>(BizErrorEnum.UNAUTHORIZED.getCode(), BizErrorEnum.UNAUTHORIZED.getDesc());
    }

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Result<?> businessExceptionHandler(BusinessException e, HttpServletResponse response) {
        CommonUtil.addCrossHeaders(response);
        return new Result<>(e.getCode(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public Result<?> exceptionHandler(Throwable e, HttpServletResponse response) {
        logger.error(e.getMessage(), e);
        CommonUtil.addCrossHeaders(response);
        return new Result<>(BizErrorEnum.RESULT_ERROR.getCode(), BizErrorEnum.RESULT_ERROR.getDesc(),null,e.getMessage());
    }

}
